import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';

class PdfMenuList extends StatefulWidget {
  const PdfMenuList({Key? key}) : super(key: key);

  @override
  _PdfMenuListState createState() => _PdfMenuListState();
}

class _PdfMenuListState extends State<PdfMenuList> {
  late List<Widget> pdfBtnList;

  _PdfMenuListState() {
    pdfBtnList = List.of([]);

    var pdfChapters = [
      "212回 我抓我自己.pdf",
      "213回 青冥剑宗沦陷？.pdf",
      "214回 一个大胆的想法.pdf",
      "215回 魔族，死！.pdf",
      "216回 红尘仙翁.pdf",
      "217回 苍穹境和皇天境.pdf",
      "218回 清理门户.pdf",
      "219回 阳仙尊.pdf",
      "220回 天帝园圃，槐江之山.pdf",
      "221回 我不是英招.pdf",
      "222回 三魂归一.pdf",
      "223回 新的天妒，东皇太一.pdf",
      "224回 筑基都筑不好要你何用.pdf",
      "225回 这就素境界碾压！.pdf",
      "226回 此处不是仙界吗？.pdf",
      "227回 举朝飞升.pdf"
    ];

    for (int i = 0; i < pdfChapters.length; i++) {
      //1.局部变量加complete 传参完成 button list初始化，还好 局部变量有效！！！
      var pdfData;
      rootBundle
          .load("pdf/${pdfChapters[i]}")
          .then((value) => pdfData = value.buffer.asUint8List())
          //2.//局部变量加complete 传参完成 button list初始化，还好 局部变量有效！！！
          .whenComplete(() {
        //成功解决 界面组件显示 不出来的问题
        setState(() {
          print("load pdf data over");
          pdfBtnList.add(TextButton(
              onPressed: () {
                getApplicationDocumentsDirectory().then((value) {
                  Directory documentsDirectory = value;
                  String path = documentsDirectory.path;
                  List<FileSystemEntity> fileList =
                      Directory(path).listSync(recursive: true);
                  for (FileSystemEntity fileSystemEntity in fileList) {
                    print('$fileSystemEntity');
                  }
                });

                getExternalStorageDirectory().then((value) {
                  print("=================");
                  print(value);
                  for (var d in value!.listSync(recursive: true)) {
                    print('$d');
                  }
                });
                print(pdfChapters[i]);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) {
                      // return PDFScreen(path: "pdf/$pdfChapters[i]");
                      return PDFScreen(
                        data: pdfData,
                      );
                    },
                  ),
                );
              },
              child: Text(pdfChapters[i])));
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // List<String> paths = List.empty();
    // var path;
    // rootBundle.load("pdf/").then((value) =>
    //   path = value
    // );
    // print(path);

    // var d = Directory("pdf");
    // print(d);
    // print(d.exists());
    // print(getApplicationDocumentsDirectory());

    return Center(
      child: ListView(
        children: pdfBtnList,
      ),
    );
  }
}

class PdfHome extends StatelessWidget {
  const PdfHome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "PDF Home",
      home: Scaffold(
        appBar: AppBar(
          title: const Text("PDF List"),
        ),
        body: const PdfMenuList(),
      ),
    );
  }
}

void main() {
  runApp(const PdfHome());
}

class PDFScreen extends StatefulWidget {
  //传路径
  final String? path;

  //传二进制数据
  final Uint8List? data;

  const PDFScreen({Key? key, this.path, this.data}) : super(key: key);

  @override
  _PDFScreenState createState() => _PDFScreenState();
}

class _PDFScreenState extends State<PDFScreen> with WidgetsBindingObserver {
  final Completer<PDFViewController> _controller =
      Completer<PDFViewController>();
  int? pages = 0;
  int? currentPage = 0;
  bool isReady = false;
  String errorMessage = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Document"),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () {},
          ),
        ],
      ),
      body: Stack(
        children: <Widget>[
          PDFView(
            // filePath: widget.path,
            pdfData: widget.data,
            enableSwipe: true,
            swipeHorizontal: false,
            autoSpacing: false,
            pageFling: true,
            pageSnap: true,
            defaultPage: currentPage!,
            fitPolicy: FitPolicy.BOTH,
            preventLinkNavigation: false,
            // if set to true the link is handled in flutter
            onRender: (_pages) {
              setState(() {
                pages = _pages;
                isReady = true;
              });
            },
            onError: (error) {
              setState(() {
                errorMessage = error.toString();
              });
              print(error.toString());
            },
            onPageError: (page, error) {
              setState(() {
                errorMessage = '$page: ${error.toString()}';
              });
              print('$page: ${error.toString()}');
            },
            onViewCreated: (PDFViewController pdfViewController) {
              _controller.complete(pdfViewController);
            },
            onLinkHandler: (String? uri) {
              print('goto uri: $uri');
            },
            onPageChanged: (int? page, int? total) {
              print('page change: $page/$total');
              setState(() {
                currentPage = page;
              });
            },
          ),
          errorMessage.isEmpty
              ? !isReady
                  ? const Center(
                      child: CircularProgressIndicator(),
                    )
                  : Container()
              : Center(
                  child: Text(errorMessage),
                )
        ],
      ),
      floatingActionButton: FutureBuilder<PDFViewController>(
        future: _controller.future,
        builder: (context, AsyncSnapshot<PDFViewController> snapshot) {
          if (snapshot.hasData) {
            return FloatingActionButton.extended(
              label: Text("Go to ${pages! ~/ 2}"),
              onPressed: () async {
                await snapshot.data!.setPage(pages! ~/ 2);
              },
            );
          }

          return Container();
        },
      ),
    );
  }
}
